package com.main.accountpermissionsmanagement.domain.account.event.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.main.accountpermissionsmanagement.application.service.AccountService;
import com.main.accountpermissionsmanagement.domain.account.entity.Account;
import com.main.accountpermissionsmanagement.domain.account.event.payload.AddAccountPayload;
import com.main.common.utils.exceptions.StackTraceLog;
import com.main.crossdomaineventmanagement.event.core.EventPublisher;
import com.main.crossdomaineventmanagement.event.model.EventMessage;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RocketMQMessageListener(
        topic = "TransactionEventsTopic",
        consumerGroup = "TransactionConsumerGroup",
        selectorType = SelectorType.TAG,
        selectorExpression = "ADD_ACCOUNT"
)
public class AddAccountHandler implements RocketMQListener<MessageExt> {
    @Resource
    private AccountService accountService;
    private final StackTraceLog stackTraceLog = new StackTraceLog();
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());  // 仅注册 JavaTime 模块

    @Autowired
    @Qualifier("rocketMQRollbackEventPublisher")
    private EventPublisher eventRollbackPublisher;
    @Autowired
    @Qualifier("rocketMQTxEventPublisher")
    private EventPublisher eventPublisher;

    @Override
    public void onMessage(MessageExt msg) {
        try {
            EventMessage event = objectMapper.readValue(msg.getBody(), EventMessage.class);
            log.info("收到用户创建消息，原始内容: {}", event.getPayload());
            handleAddAccountEvent(event.getPayload());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理 "ADD_ACCOUNT" 事件
     */
    private void handleAddAccountEvent(String payload) {
        log.info("收到创建账号消息");
        log.info(payload);
        AddAccountPayload addAccountPayload = null;
        try {
            // 反序列化 payload 为业务对象
            addAccountPayload = objectMapper.readValue(payload, AddAccountPayload.class);
            try{
              Account account = accountService.addAccount(addAccountPayload.getUserId(), addAccountPayload.getName());
              registerSuccessEvent(account, addAccountPayload.getClientId());
            }catch (Exception e){
                try{
                    sendRollbackEvent(addAccountPayload.getUserId());
                }catch (Exception ex){
                    log.info("执行用户回滚消息发送方法失败");
                    stackTraceLog.saveStackTraceLog(ex);
                }
                stackTraceLog.saveStackTraceLog(e);
            }
        } catch (JsonProcessingException e) {
            System.err.println("反序列化 payload 失败: " + e.getMessage());
        }
    }

    public void sendRollbackEvent(Long userId){
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("userId", userId);
            String payloadJson = new ObjectMapper().writeValueAsString(payload);
            EventMessage event = new EventMessage("ROLLBACK_USER", "account-management", payloadJson);
            log.info("开始发送用户回滚消息,用户ID：{}", userId);
            eventRollbackPublisher.publish(event);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize event", e);
        }
    }

    public void registerSuccessEvent(Account account,Long clientId){
        try {
            Map<String, Object> payload = new HashMap<>();
            payload.put("number", account.getNumber());
            payload.put("password", account.getPassword());
            payload.put("clientId", clientId);
            String payloadJson = new ObjectMapper().writeValueAsString(payload);
            EventMessage event = new EventMessage("REGISTER_SUCCESS", "account-management", payloadJson);
            log.info("开始发送账号创建成功消息,用户ID：{}", account);
            eventPublisher.publish(event);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize event", e);
        }
    }

}